//
//  MyInfoViewController.m
//  Jingjing
//
//  Created by user on 15/11/9.
//  Copyright © 2015年 Mikeshihua. All rights reserved.
//

#import "MyInfoViewController.h"
#import "LoginViewController.h"
@interface MyInfoViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>

@property (nonatomic,retain)UITableView *myTableView;


@property (nonatomic,retain)NSArray *firstTitleNameArr;


@property (nonatomic,retain)NSArray *firstPlaceArr;


@property (nonatomic,retain)UITextField *nameTf;
@property (nonatomic,retain)UITextField *sexTf;

@property (nonatomic,retain)UITextField *contactTf;
@property (nonatomic,retain)UITextField *emailTf;

@property (nonatomic,retain)UITextField *addressTf;
@property (nonatomic,retain)UITextField *zipCodeTf;
@property (nonatomic,retain)UITextField *positionTf;
@property (nonatomic,retain) UIButton * saveBtn;


@property (nonatomic,retain)NSArray *userInfoArray;

@property(nonatomic,retain)UIScrollView *scrollView;//最底层的scrollView

@end

@implementation MyInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];

    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64.0f, SCREEN_WIDTH, SCREEN_HEIGHT-64.0f)];
    self.scrollView.backgroundColor = kColorGrayBackground;
    self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT-64.0f+16.0f);
    [self.view addSubview:self.scrollView];
    
    TopView *topView = [[TopView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"个人资料"];
    [self.view addSubview:topView];
    
    UIButton * backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10.0f, 20.0f, 44.0f, 44.0f)];
    [backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnCLick:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [topView addSubview:backBtn];
    
    
    _saveBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-54.0f, 20.0f, 44.0f, 44.0f)];
    [_saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    _saveBtn.titleLabel.font = [UIFont systemFontOfSize:16.0f];
    _saveBtn.titleLabel.textColor = [UIColor hexStringToColor:@"#FFFFFF"];
    [_saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _saveBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [topView addSubview:_saveBtn];
    
    
    [self layoutTableview];
    

    
    self.userInfoArray = [AccountTools getUserInformation];
    
   
}

- (void)backBtnCLick:(UIButton*)btn
{
    [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)layoutTableview
{
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(16.0f ,0,SCREEN_WIDTH-32.0f ,SCREEN_HEIGHT-64.0f) style:UITableViewStylePlain];
    self.myTableView.backgroundColor = kColorGrayBackground;
    self.myTableView.showsVerticalScrollIndicator = NO;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.scrollEnabled = NO;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardhide)];
    tapGesture.cancelsTouchesInView = NO;
    [self.myTableView addGestureRecognizer:tapGesture];
    
    [self.scrollView addSubview:self.myTableView];

    
    self.firstTitleNameArr = [NSArray arrayWithObjects:@"姓名",@"性别",@"手机",@"邮箱",@"地址",@"邮编",@"职业",  nil];
    self.firstPlaceArr = [NSArray arrayWithObjects:@"请填写您的姓名",@"请填写您的性别",@"请填写您的手机",@"请填写您的邮箱",@"请填写您的地址",@"请填写您的邮编",@"请填写您的职业", nil];
   

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 7;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        
        UIView * separtor = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 59.5f, SCREEN_WIDTH - 32.0f, 0.5)];
        separtor.backgroundColor =  [UIColor hexStringToColor:@"#bdbdbd"];
        separtor.tag = 111;
        [cell.contentView addSubview:separtor];//分割线
        
        UILabel *mainLabel = [[UILabel alloc]init];
        mainLabel.tag = 1;
        mainLabel.frame = CGRectMake(24.0f ,16.0f ,80.0f ,28.0f );
        mainLabel.textColor =  kColorTEXT;;
        mainLabel.font = [UIFont systemFontOfSize:16.0];
        [cell.contentView addSubview:mainLabel];
        
        
        
        UITextField * textField = [[UITextField alloc]init];
        textField.tag = 2 ;
        textField.frame = CGRectMake(104.0f, 16.0f, SCREEN_WIDTH - 112.0f-48.0f,28.0f);
        textField.font = [UIFont systemFontOfSize:16.0f];
        textField.textColor = kColorTEXT;
        textField.delegate = self;

        textField.borderStyle = UITextBorderStyleNone;
        textField.textAlignment = NSTextAlignmentRight;
        [cell.contentView  addSubview:textField];
    }

    
    UILabel *mainLabel = (UILabel*)[cell.contentView viewWithTag:1];
    UITextField * textField = (UITextField*)[cell.contentView viewWithTag:2];
    UIView *separtor = (UIView*)[cell.contentView viewWithTag:111];
    
    if (indexPath.row==self.firstPlaceArr.count-1) {
        separtor.hidden = YES;
    }else{
        separtor.hidden = NO;
    }
    
    mainLabel.text = [self.firstTitleNameArr objectAtIndex:indexPath.row];

        if (indexPath.row==0) {
            
            textField.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"userName"]; //注册时的名字
            self.nameTf = textField;
            
            
        }else if (indexPath.row==1){
            
            if ([AccountTools isEmpty:[[NSUserDefaults standardUserDefaults]objectForKey:@"sex"]]==YES) {
                textField.placeholder = [self.firstPlaceArr objectAtIndex:indexPath.row];
                textField.text = @"";
            }else{
                
                if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"sex"]isEqualToString:@"0"]) {
                     textField.text = @"男";
                }else if([[[NSUserDefaults standardUserDefaults]objectForKey:@"sex"]isEqualToString:@"1"]) {
                    textField.text = @"女";
                }else{
                    
                }
               
            }
            self.sexTf = textField;
        }else if (indexPath.row==2){
            if ([AccountTools isEmpty:[[NSUserDefaults standardUserDefaults]objectForKey:@"userCd"]]==YES) {
                textField.placeholder = [self.firstPlaceArr objectAtIndex:indexPath.row];
                textField.text = @"";
            }else{
                textField.placeholder = [[NSUserDefaults standardUserDefaults]objectForKey:@"userCd"];
                textField.text = textField.placeholder;
            }
           
            self.contactTf = textField;
            self.contactTf.enabled = NO;
            
        }else if (indexPath.row==3){
            
            if ([AccountTools isEmpty:[[NSUserDefaults standardUserDefaults]objectForKey:@"email"]]==YES) {
                textField.placeholder = [self.firstPlaceArr objectAtIndex:indexPath.row];
                textField.text = @"";
            }else{
                textField.placeholder = [[NSUserDefaults standardUserDefaults]objectForKey:@"email"];
                textField.text = textField.placeholder;
            }
           
            self.emailTf = textField;
        }else if (indexPath.row==4){
            if ([AccountTools isEmpty:[[NSUserDefaults standardUserDefaults]objectForKey:@"address"]]==YES) {
                textField.placeholder = [self.firstPlaceArr objectAtIndex:indexPath.row];
                textField.text = @"";
            }else{
                textField.placeholder = [[NSUserDefaults standardUserDefaults]objectForKey:@"address"];
                textField.text = textField.placeholder;
            }
            
            self.addressTf = textField;
        }else if (indexPath.row==5){
            if ([AccountTools isEmpty:[[NSUserDefaults standardUserDefaults]objectForKey:@"zipCode"]]==YES) {
                textField.placeholder = [self.firstPlaceArr objectAtIndex:indexPath.row];
                textField.text = @"";
            }else{
                textField.placeholder = [[NSUserDefaults standardUserDefaults]objectForKey:@"zipCode"];
                textField.text = textField.placeholder;
            }
            
            self.zipCodeTf = textField;
        }else if (indexPath.row==6){
            if ([AccountTools isEmpty:[[NSUserDefaults standardUserDefaults]objectForKey:@"position"]]==YES) {
                textField.placeholder = [self.firstPlaceArr objectAtIndex:indexPath.row];
                textField.text = @"";
            }else{
                textField.placeholder = [[NSUserDefaults standardUserDefaults]objectForKey:@"position"];
                textField.text = textField.placeholder;
            }
            
            self.positionTf = textField;
        }
    
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.0f;
}
- (void)saveBtnClick
{
    [self.view endEditing:YES];
    
    _saveBtn.hidden = YES;
    if ([AccountTools isEmpty:self.nameTf.text]==YES) {
        ALERT_VIEW(@"姓名是必填的哦,请重新输入");
        _saveBtn.hidden = NO;
        return;
        
    }
    [self httpRequest];
    
    

}

- (void)httpRequest
{
    
    if (self.nameTf.text.length>30) {
        ALERT_VIEW(@"用户名长度不能超过30个字符哦")
        _saveBtn.hidden = NO;
        return;
    }
    
     NSString *sexStr = self.sexTf.text;
    if ([AccountTools isEmpty:sexStr]==NO) {
        if ([sexStr isEqualToString:@"男"]||[sexStr isEqualToString:@"女"]) {
            
            if ([sexStr isEqualToString:@"男"]) {
                sexStr = @"0";
            }else if ([sexStr isEqualToString:@"女"])
            {
                sexStr = @"1";
            }
            
        }else{
            ALERT_VIEW(@"性别输入只能为男或女哦");
            _saveBtn.hidden = NO;
            return;
        }

    }
    

    
    if ([AccountTools isEmpty:self.contactTf.text]==NO &&[AccountTools validatePhoneNumber:self.contactTf.text]==NO) {
        ALERT_VIEW(@"手机号输入不合法,请重新输入");
        _saveBtn.hidden = NO;
        return;
    }
    
    if ([AccountTools isEmpty:self.emailTf.text]== NO&& [AccountTools validateEmail:self.emailTf.text]==NO) {
        ALERT_VIEW(@"邮箱输入不合法,请重新输入");
        _saveBtn.hidden = NO;
        return;
    }
    
    if ([AccountTools isEmpty:self.emailTf.text]==NO) {
        if (self.emailTf.text.length>30) {
            ALERT_VIEW(@"邮箱最多只能输入30个字符,请重新输入");
            _saveBtn.hidden = NO;
            return;
        }
    }
    
    if (self.addressTf.text.length>50) {
        ALERT_VIEW(@"地址长度不能超过50个字符哦")
        _saveBtn.hidden = NO;
        return;
    }
    
    
    if ([AccountTools isEmpty:self.zipCodeTf.text]==NO&&[AccountTools allIsNumber:self.zipCodeTf.text]==NO) {
        ALERT_VIEW(@"邮编输入必须为数字,请重新输入");
        _saveBtn.hidden = NO;
        return;
        
    }
    
    if ([AccountTools isEmpty:self.zipCodeTf.text]==NO) {
        if (self.zipCodeTf.text.length !=6) {
            ALERT_VIEW(@"邮编输入必须6位数字,请重新输入");
            _saveBtn.hidden = NO;
            return;
        }

    }
    
    if (self.positionTf.text.length>30) {
        ALERT_VIEW(@"职业不能超过30个字符哦");
        _saveBtn.hidden = NO;
        return;
    }
    
    
    //    执行
    [[AnimationIndicator sharedIndicator] startAnimationWithLoadText:@"加载中..."];
    [AppGlobalClass PostDataWithNSstring:UPDATEUSERINFO withDictionary:@{@"token":[[NSUserDefaults standardUserDefaults]objectForKey:@"token"],@"userName":self.nameTf.text,@"mobile":self.contactTf.text,@"address":self.addressTf.text,@"email":self.emailTf.text,@"sex":sexStr,@"zipCode":self.zipCodeTf.text,@"position":self.positionTf.text} success:^(NSDictionary *dictionary) {
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
           
            [AccountTools SaveUserToken:[[NSUserDefaults standardUserDefaults]objectForKey:@"token"] userName:self.nameTf.text userCd:self.contactTf.text address:self.addressTf.text email:self.emailTf.text zipCode:self.zipCodeTf.text position:self.positionTf.text sex:sexStr];
          
            ALERT_VIEW(@"设置成功")
            [self.navigationController popViewControllerAnimated:YES];
        }else
        {
            NSString * str = [dictionary objectForKey:@"message"];
            ALERT_VIEW(str);
        }
        _saveBtn.hidden = NO;
        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    } failure:^(NSError *error) {
        _saveBtn.hidden = NO;
        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    } networkerror:^(NSString *networkerror) {
        _saveBtn.hidden = NO;
        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    }];
    
    
    
}





- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = TRUE;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardShow:)
                                                 name: UIKeyboardDidShowNotification object:nil];
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardHide:)
                                                 name: UIKeyboardDidHideNotification object:nil];
    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloginView) name:@"reLogin" object:nil];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = FALSE;
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)reloginView
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"账号在另一台机器登录，请重新登录!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
#pragma mark------------alertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //删除token等用户数据
    [AccountTools exitLogin];
    LoginViewController *loginViewCon = [[LoginViewController alloc]init];
    loginViewCon.backBtHide = FALSE;
    [self presentViewController:loginViewCon animated:TRUE completion:^{
        
        [self.navigationController popViewControllerAnimated:FALSE];
        
    }];
    
}


//隐藏键盘
-(void)keyboardhide
{
    
    [self.myTableView endEditing:YES];
}




//当键盘出现或改变时调用
- (void)keyboardShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT+height-64.0f);
}
//当键盘退出或改变时调用
- (void)keyboardHide:(NSNotification *)aNotification
{
    self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT-64.0f+16.0f);
}

@end
